<template>
    <el-dialog :model-value="show" title="设置排序" @close="emit('hide')">
      <el-form ref="formRef" :model="form" >
        <el-form-item label="秒杀时间段名称" prop="username" style="width: 300px;">
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submitFn">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </template>
  <script setup lang="ts">
  import { reactive, ref, watch } from "vue";
  import { ElMessageBox, FormInstance ,ElMessage} from "element-plus";
  import { addFlashSessionCreate,FlashSessionUpdate,getFlashSessionById} from "./api";
  
  const props = defineProps({
    show: {
      type: Boolean,
      default: false,
    },
    id: {
      type: Number,
      default: 0
    }
  });
  
  watch(
    () => props.id,
    () => {
      if (props.id !== 0) {
        getFlashSessionById(props.id).then((res) => {
          if (res.code === 200) {
            Object.assign(form, res.data)
          }
        });
      }else{
    formRef.value?.resetFields();
  }
    }
  );
  
  const cancel = ()=>{
    emit("hide");
  }
  
  const emit = defineEmits(["hide"]);
  
  const form = reactive<TimeListModel>({
    endTime: '',
    startTime: '',
    status: 0,
    name: ''
  });
  
  
  const formRef = ref<FormInstance>();
  
  const add = () => {
    ElMessageBox.confirm("确定要添加用户吗？", "添加用户", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        addFlashSessionCreate(form).then((res) => {
          if (res.code === 200) {
            ElMessage.success('添加成功')
            emit("hide", true);
            formRef.value?.resetFields();
          }
        });
      })
      .catch(() => {
  
      });
  };
  
  const change = () => {
    ElMessageBox.confirm("确定要修改当前用户的修改吗？", "修改用户信息", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        FlashSessionUpdate(form).then((res) => {
          if (res.code === 200) {
            ElMessage.success("修改成功");
            formRef.value?.resetFields();
            emit("hide", true);
          }
        });
      })
      .catch(() => {});
  };
  
  const submitFn = () => {
    formRef.value?.validate((ok: boolean) => {
      if (ok) {
        if (props.id === 0) {
            add();
        } else {
            change();
        }
      } else {
      }
    });
  };
  </script>
  <style lang="less" scoped>
  
  </style>
    